#include<bits/stdc++.h>
using namespace std;
int main(){
  freopen("guess.in","r",stdin);
  freopen("guess.out","w",stdout);
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  int t; cin>>t;
  while(t--){
    int n,c=0; cin>>n;
    vector<int> a(n+1); cin>>a[0];
    static int A,B,C,M; cin>>A>>B>>C>>M;
    auto gen=[&](int x,int y,int z){
      int c=x;
      if((c+=y)>=M)c-=M;
      if((c+=z)>=M)c-=M;
      return c;
    };
    for(int i=1;i<=n;i++)
      a[i]=gen(1ll*A*a[i-1]%M*a[i-1]%M,1ll*B*a[i-1]%M,C)+1;
  }
  return 0;
}